package pers.chao.tool.encrypt;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * Description: aes对称加密解密
 *
 * @author W.Chao
 * @date 2020/11/14 18:39
 **/
public final class EasyAes {
	private static final String AES = "AES";

	/**
	 * AES解密
	 *
	 * @param encryptValue 待解密内容
	 * @param key          秘钥
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String encryptValue, String key) throws Exception {
		return aesDecryptByBytes(base64Decode(encryptValue), key);
	}

	/**
	 * AES加密
	 *
	 * @param value 待加密内容
	 * @param key   秘钥
	 * @return
	 * @throws Exception
	 */
	protected static String encrypt(String value, String key) throws Exception {
		return base64Encode(aesEncryptToBytes(value, key));
	}

	private static String base64Encode(byte[] bytes) {
		return EasyBase64.encrypt(bytes);
	}

	@SuppressWarnings("static-access")
	private static byte[] base64Decode(String base64Code) throws Exception {
		return base64Code == null ? null : EasyBase64.decrypt(base64Code);
	}

	private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
		keyGenerator.init(128, new SecureRandom(encryptKey.getBytes()));

		Cipher cipher = Cipher.getInstance(AES);
		cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyGenerator.generateKey().getEncoded(), AES));

		return cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
	}

	private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
		keyGenerator.init(128, new SecureRandom(decryptKey.getBytes()));

		Cipher cipher = Cipher.getInstance(AES);
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyGenerator.generateKey().getEncoded(), AES));
		byte[] decryptBytes = cipher.doFinal(encryptBytes);

		return new String(decryptBytes);
	}
}
